import { storageKey } from '~/config'

interface IStoredItem {
  value: any
  expires?: number
}
enum StorageType {
  l = 'localStorage',
  s = 'sessionStorage',
}

export class Memory {
  storage: Storage
  constructor(type: StorageType) {
    this.storage
      = type === StorageType.l ? window.localStorage : window.sessionStorage
  }

  private synthesisKey(key: string) {
    return storageKey + key
  }

  set(key: string, value: any, expires?: number) {
    const source: IStoredItem = { value: null }
    if (expires && expires > 0)
      source.expires = expires

    source.value = value
    const data = JSON.stringify(source)
    this.storage.setItem(this.synthesisKey(key), data)
  }

  get(key: string) {
    const value = this.storage.getItem(this.synthesisKey(key))
    if (value) {
      const source: IStoredItem = JSON.parse(value)
      const expires = source.expires
      const now = new Date().getTime()
      if (expires && now > expires) {
        this.delete(key)
        return null
      }
      return source.value
    }
  }

  delete(key: string) {
    this.storage.removeItem(this.synthesisKey(key))
  }

  clear() {
    this.storage.clear()
  }
}

export default new Memory(StorageType.l)
